module FollowHttpRedirects
  def self.get_response_following_redirects orig_uri, requests_limit = 15
    raise "Input must be an absolute URI." unless orig_uri.is_a?(URI::Generic) && orig_uri.absolute?

    uri = orig_uri
    requests_made = 0
    while requests_made <= requests_limit
      response = Net::HTTP.get_response uri
      requests_made += 1
      case response
        when Net::HTTPSuccess
          return response
        when Net::HTTPRedirection
          redirect_url = response.header['location']
          unless redirect_url.is_a?(String) && !redirect_url.empty?
            raise "Redirect Error, no redirect location specified."
          end

          temp_uri = URI(redirect_url)
          if temp_uri.relative?
            uri = uri.merge temp_uri #make URI absolute
          else
            uri = temp_uri
          end
        else
          raise "Don't know what to do with this response: #{response.inspect}"
      end
    end
    raise "Too many redirects (#{requests_limit}) error"
  end
end
